import $ from "jquery";
import Store from "store2";
import fetchParam from "./utils";
import headerTpl from "../components/header/index.ejs";
import listTpl from "../components/list/index.ejs";

(($) => {
  let params = {
    type: fetchParam("type"),
    id: fetchParam("id") || "",
  };

  const methods = {
    computedTitle: ({ type, id }) => {
      if (type === "people") {
        return "选人";
      }
      if (type === "restaurant" && id) {
        return "选套餐";
      }
      if (type === "restaurant") {
        return "选餐厅";
      }
      return "";
    },

//  fetchData: ({ title, key }) => {
//   return new Promise((resolve, reject) => {
//     $.ajax({
//       type: 'GET',
//       url: './../data/data.json',
//       success: function (res) {
//         resolve({
//           header: {
//             title,
//             link: {
//               title: 'Back',
//               href: './order.html'
//     computedType: ({ type, id }) => {
//       if (type === "restaurant" && id) {
//         return "meal";
//       }
//       return type;
//     },

    fetchData: ({ id = "", type, key }) => {
      return new Promise((resolve, reject) => {
        $.ajax({
          type: "GET",
          url: "/data/data.json",
          success: (res) => {
            if (key === "meal") {
              const { menu = [] } = res[type].find((_) => _.id == id) || {};
              resolve({
                data: menu.map((_) =>
                  Object.assign({}, _, {
                    sum: 1,
                  })
                ),
              });
            }
            resolve({ data: res[type] });
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },

    bindStoreEvent: (selector) => {
      const { key, store = [] } = params;
      $(selector).on("click", function (e) {
        const { id, value } = $(this).data();
        if (key == "people") {
          Store.set(key, value);
        }
        if (key === "restaurant") {
          Store.set(key, { id, value });
          Store.has("meal") && Store.remove("meal");
        }
        if (key === "meal") {
          const data = store.find((_) => _.id == id) || {};
          Store.set(key, data);
        }
        location.href = "order.html";
        e.preventDefault();
      });
    },

    bindSumEvent: (selector) => {
      const { store = [] } = params;
      $(selector).on("click", function (e) {
        const { id, action = "" } = $(this).data();
        if (action === "decrease") {
          params["store"] = store.map((_) => {
            if (_.id == id) {
              return Object.assign({}, _, {
                sum: Math.max(1, _.sum - 1),
              });
            }
            return _;
          });
        }
        if (action === "increase") {
          params["store"] = store.map((_) => {
            if (_.id == id) {
              return Object.assign({}, _, {
                sum: _.sum + 1,
              });
            }
            return _;
          });
        }
        methods.renderListView(".meal-option", ".page-list");
        methods.bindSumEvent(".button__number");
        methods.bindStoreEvent(".button");
        e.preventDefault();
        e.stopPropagation();
      });
    },

    renderHeaderView: (selector) => {
      const { title } = params;
      const headerEl = headerTpl({
        title,
        link: {
          title: "Back",
          href: "./order.html",
        },
      });
      $(selector).append(headerEl);
    },

    renderListView: (wrappedSelector, selector) => {
      $(wrappedSelector) && $(wrappedSelector).remove();
      const { key, store = [] } = params;
      const listEl = listTpl({
        type: key,
        data: store,
      });
      $(selector).append(listEl);
    },

// store.set('a', 1);
// if (type === 'people') {

//   console.log(headerTpl);
//   $('.page-list').append(headerTpl);
//   $.getJSON('./../data/data.json', function (res) {
//     const { people = [] } = res;
//     const listTpl = list({
//       type,
//       data: people
//     })
//     $('.page-list').append(listTpl);
//   });
// } else if (type === 'restaurant') {
//   const headerTpl = header({
//     title: '选餐厅',
//     link: {
//       title: 'Back',
//       href: './order.html'
//     }
//   });
//   $('.page-list').append(headerTpl);
//   $.getJSON("./../data/data.json", function (res) {
//     const { shop = [] } = res;
//     const listTpl = list({
//       type,
//       data: shop
//     })
//     $('.page-list').append(listTpl);
//   });
// } else if (type === 'menu') {
//   const headerTpl = header({
//     title: '选套餐',
//     link: {
//       title: 'Back',
//       href: './order.html'
//     }
//   });
//   $('.page-list').append(headerTpl);
    initData: async () => {
      params["title"] = methods.computedTitle(params);
      params["key"] = methods.computedType(params);
      try {
        const { data = [] } = await methods.fetchData(params);
        params["store"] = data;
        methods.renderHeaderView(".page-list");
        methods.renderListView(".meal-option", ".page-list");
        methods.bindStoreEvent(".button");
        methods.bindSumEvent(".button__number");
      } catch (error) {
        console.error(error);
      }
    },
  };

  methods.initData();
})($);
